package com.tio.tiowebscoketdemo.handler.bus;

import cn.hutool.json.JSONUtil;
import com.tio.tiowebscoketdemo.common.WsBusType;
import com.tio.tiowebscoketdemo.common.intf.AbsShowcaseBsHandler;
import com.tio.tiowebscoketdemo.common.packets.LoginReqBody;
import com.tio.tiowebscoketdemo.common.packets.LoginRespBody;
import com.tio.tiowebscoketdemo.config.CaseServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.json.Json;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

/**
 * @author tanyaowu
 * 2017年3月27日 下午9:51:28
 */
public class LoginReqHandler extends AbsShowcaseBsHandler<LoginReqBody> {
	private static Logger log = LoggerFactory.getLogger(LoginReqHandler.class);

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {

	}

	/**
	 *
	 * @author tanyaowu
	 */
	public LoginReqHandler() {
	}

	/**
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Class<LoginReqBody> bodyClass() {
		return LoginReqBody.class;
	}

	/**
	 * @param wsRequest
	 * @param bsBody
	 * @param channelContext
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public Object handler(WsRequest wsRequest, LoginReqBody bsBody, ChannelContext channelContext) throws Exception {
		log.info("收到登录请求消息:{}", Json.toJson(bsBody));

		String token = bsBody.getToken();
		//TODO 解析userid
		String userid = "123";
		Tio.bindUser(channelContext, userid);

		LoginRespBody loginRespBody = new LoginRespBody();
		loginRespBody.setCode(LoginReqBody.Code.SUCCESS);
		loginRespBody.setToken("用户token解析成功");
		loginRespBody.setType(WsBusType.LOGIN_RESP);

		WsResponse wsResponse = WsResponse.fromText(JSONUtil.toJsonStr(loginRespBody), CaseServerConfig.CHARSET);
		Tio.send(channelContext, wsResponse);
		//Tio.sendToUser(channelContext.tioConfig, userid, wsResponse);
		return null;
	}

}
